let canvas, context, 
canvasWidth =  Math.min(800,document.body.clientWidth-10), 
canvasHeight =  600;
let balls = [];
let littleBalls = []
let isMoving = true;
let words = "人口手耳头牙";
let colors = ["#f7acbc", "#f05b72", "#f58220", "#d93a49", "#5f3c23", "#f26522", "#80752c", "#2e3a1f", "#5c7a29", "#bed742", "#007d65"];
let curIndex;
let isOver = false;
document.querySelector("#btnController").onclick = function () {
    if (isMoving) {
        isMoving = false;
        this.innerText = "开始运动";
    } else {
        isMoving = true;
        this.innerText = "停止运动";
    }

}

window.onload = function () {
    canvas = document.querySelector("#canvas");
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    context = canvas.getContext("2d");
    //重叠时基础图层上暗的部分更暗，亮的部分更亮
    //context.globalCompositeOperation = "overlay";
    init();
    animation();
    canvas.addEventListener("mouseup", touch);
    canvas.addEventListener("touchend", touch);          
    document.querySelector("#txt").onblur = function () {
        words = document.querySelector("#txt").value;
        balls = [];
        init();
    }
}

function animation() {
    render();
    update();
    if (balls.length > 0)
        requestAnimationFrame(animation);
    else
        requestAnimationFrame(animation);
}

//初始化小球
function init() {
    for (let i = 0; i < words.length; i++) {
        let r = Math.random() * 5 + canvasWidth/8;
        let ball = {
            color: colors[Math.floor(Math.random() * colors.length)],
            radius: r,
            x: Math.random() * (canvasWidth - 2 * r) + r,
            y: Math.random() * (canvasHeight - 2 * r) + r,
            vx: (Math.random() * 1.5 + 0.5) * (Math.random() > 0.5 ? 1 : -1),
            vy: (Math.random() * 1.5 + 0.5) * (Math.random() > 0.5 ? 1 : -1),
            word: words[i]
        };
        balls.push(ball);
    }
    curIndex = Math.floor(Math.random() * words.length);
    document.querySelector("#curWord").innerText = balls[curIndex].word;
    isOver = false;
}
function render() {
    let ctx = context;
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.save();

    ctx.fillStyle = "#f8aba6";
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
    ctx.restore();
    for (let i = 0; i < balls.length; i++) {
        ctx.save();
        //阴影
        ctx.shadowColor = "#CCC";
        ctx.shadowBlur = 5;
        ctx.shadowOffsetX = 5;
        ctx.shadowOffsetY = 5;

        grd = ctx.createRadialGradient(balls[i].x - 20, balls[i].y - 20, 2, balls[i].x - 20, balls[i].y - 20, balls[i].radius);
        grd.addColorStop(0, '#CCC');
        grd.addColorStop(1, balls[i].color);
        ctx.fillStyle = grd;
        ctx.beginPath();
        ctx.arc(balls[i].x, balls[i].y, balls[i].radius, 0, Math.PI * 2);
        ctx.closePath();
        ctx.fill();
        ctx.restore();
        ctx.fillStyle = "red";
        let fontSize = canvasWidth/8;
        ctx.font = 'normal bold '+fontSize+'px 仿宋';
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";

        ctx.fillText(balls[i].word, balls[i].x, balls[i].y);
    }
    ctx.restore();
    if (isOver)
        over();
}
function update() {
    if (!isMoving)
        return;
    for (let i = 0; i < balls.length; i++) {
        balls[i].x += balls[i].vx;
        balls[i].y += balls[i].vy;
        if (balls[i].x < balls[i].radius) {
            balls[i].x = balls[i].radius;
            balls[i].vx *= -1;
        }
        if (balls[i].y < balls[i].radius) {
            balls[i].y = balls[i].radius;
            balls[i].vy *= -1;
        }

        if (balls[i].x > canvasWidth - balls[i].radius) {
            balls[i].x = canvasWidth - balls[i].radius;
            balls[i].vx *= -1;
        }
        if (balls[i].y > canvasHeight - balls[i].radius) {
            balls[i].y = canvasHeight - balls[i].radius;
            balls[i].vy *= -1;
        }
    }
}
function touch(event) {
    let x = event.clientX - canvas.getBoundingClientRect().left;
    let y = event.clientY - canvas.getBoundingClientRect().top;

    if (balls.length > 0) {
        context.beginPath();
        context.arc(balls[curIndex].x, balls[curIndex].y, balls[curIndex].radius, 0, Math.PI * 2);

        if (context.isPointInPath(x, y)) {
            init2();
            explode();
            balls.splice(curIndex, 1);
            if (balls.length > 0) {
                curIndex = Math.floor(Math.random() * balls.length);
                document.querySelector("#curWord").innerText = balls[curIndex].word;
            } else {
                isOver = true;
            }
        }
    }
}
function explode() {
    update2();
    draw2();
    if (littleBalls.length == 0)
        cancelAnimationFrame(explode);
    else
        requestAnimationFrame(explode);
}

function init2() {
    littleBalls = null;
    littleBalls = [];
    for (let i = 0; i < 50; i++) {
        let vx = (Math.random() * 3 + 2) * (Math.random() > 0.5 ? 1 : -1);
        let vy = -((Math.random() * 2 + 2)) * (Math.random() > 0.5 ? 1 : -1);
        let ball = {
            color: colors[Math.floor(Math.random() * colors.length)],
            radius: canvasWidth/8/4,
            x: balls[curIndex].x + Math.random() * 10 + 5,
            y: balls[curIndex].y + Math.random() * 10 + 5,
            vx: vx,
            vy: vy,
            g: 0.5 + Math.random()

        };

        littleBalls.push(ball);
    }
}
function update2() {
    for (let i = 0; i < littleBalls.length; i++) {
        littleBalls[i].x += littleBalls[i].vx;
        littleBalls[i].y += littleBalls[i].vy;
        littleBalls[i].vy += littleBalls[i].g;//向下加速度
        //console.log(littleBalls[0].vx,littleBalls[0].vy,littleBalls[0].g);
        //如果倒低就反弹
        if (littleBalls[i].y > canvasHeight - littleBalls[i].radius) {
            littleBalls[i].y = canvasHeight - littleBalls[i].radius;
            littleBalls[i].vy = -littleBalls[i].vy * 0.85;//增加摩擦系数，越来越矮
        }
    }
    let cnt = 0;
    for (let i = 0; i < littleBalls.length; i++) {
        if (littleBalls[i].x - littleBalls[i].radius > 0 && littleBalls[i].x + littleBalls[i].radius < canvasWidth)
            littleBalls[cnt++] = littleBalls[i];
    }
    //弹出不在屏幕范围内的小球
    while (littleBalls.length > cnt) {
        littleBalls.pop();
    }

}
function draw2() {
    for (let i = 0; i < littleBalls.length; i++) {
        context.fillStyle = littleBalls[i].color;
        context.beginPath();
        context.arc(littleBalls[i].x, littleBalls[i].y, littleBalls[i].radius, 0, 2 * Math.PI);
        context.closePath();
        context.fill();
    }
}
function over() {
    let ctx = context;
    let img = document.createElement("img");
    img.src = './img/good.gif';
    img.width = 300;
    img.height = 300;
    ctx.save();
    let pattern = context.createPattern(img, "no-repeat");
    ctx.fillStyle = pattern;
    ctx.fillRect(0, 0, 300, 300);
    ctx.restore();
}
